__author__='adsas'

print('这是我的第一个Python程序');
print('你好'.encode('utf-8'));
print(10/3);
print(10//3);
print(type(10));
ttttt=type(10);
print(ttttt.__name__);
print(len('你好'));
print(len(b'\xe4\xb8\xad\xe6\x96\x87'));
print('这是一个替换符%s' % ('nihao'));
_list=['1','2',1,10];
print(_list);
_list.append('新增的元素');
print(_list);
_list.pop(1);
print('这是:%s' % (type(_list).__name__),_list);
_trup=(1,2,3,'as');
print('这是:%s' % (type(_trup).__name__),_trup);
#age = input();
#age=int(age);
#if age >= 18:
#    print('your age is', age);
#    if age>80:
#        print('老年');
#    print('已成年');
#else:
#    print('未成年')

for item in _list:
    print('循环输出_list：',item)
_range=range(100);
print(type(_range).__name__);
#for x in _range:
#    if x%2==0:
#        continue;
#    print(x);

_dic={'1':'11','2':232,'4':'dd'};
for x in _dic:
    print(x,':',_dic[x]);
s=_dic.get(4);
print(s is None);

s=['4s',2,3,'1s',1,3,4,5];
print(type(s).__name__,s);
s=set(s);
print(type(s).__name__,s);
print(hex(1));

#from MyFunction import myabs;
#print(myabs(-10));


#myabs();

import MyFunction;
a=MyFunction.myabs(-1);
print(a);
a=MyFunction.manyreturn('1','3',2);
print(type(a).__name__,a);

#print(MyFunction.quadratic(10,15,20));

print(MyFunction.porew(2.2,2))

#MyFunction.add_end(['d','s']);
#MyFunction.add_end();
#MyFunction.add_end();
#MyFunction.add_end();

#MyFunction.kebiancanshu('name',*[1,2,3]);
#_dic["12"]=1;
#_dic.setdefault('12',22);
#MyFunction.guaniacicanshu('小米',10,**_dic);

#MyFunction.f1('name',*['aaa','sss'],d='asads',asd=55,ass=2,f=15);

#MyFunction.product();
#print('product() =', MyFunction.product())
#print('product(5) =', MyFunction.product(5))
#print('product(5, 6) =', MyFunction.product(5, 6))
#print('product(5, 6, 7) =', MyFunction.product(5, 6, 7))
#print('product(5, 6, 7, 9) =', MyFunction.product(5, 6, 7, 9))

#if MyFunction.product(5) != 5:
#    print('测试失败!')
#elif MyFunction.product(5, 6) != 30:
#    print('测试失败!')
#elif MyFunction.product(5, 6, 7) != 210:
#    print('测试失败!')
#elif MyFunction.product(5, 6, 7, 9) != 1890:
#    print('测试失败!')
#else:
#    try:
#        MyFunction.product()
#        print('测试失败!')
#    except TypeError:
#        print('测试成功!')

#print('fact(1000) =', MyFunction.fact1(1000));


#list=list(range(100));
#print(list);

#print(list[:-1]);
#print(list[1:99]);
#print(MyFunction.trim('hello  '))
#print(MyFunction.trim('  hello'))
#print(MyFunction.trim('  hello  '))
#print(MyFunction.trim('  hello  world  '))
#print(MyFunction.trim(''))
#print(MyFunction.trim('    '))
#if MyFunction.trim('hello  ') != 'hello':
#    print('测试失败!')
#elif MyFunction.trim('  hello') != 'hello':
#    print('测试失败!')
#elif MyFunction.trim('  hello  ') != 'hello':
#    print('测试失败!')
#elif MyFunction.trim('  hello  world  ') != 'hello  world':
#    print('测试失败!')
#elif MyFunction.trim('') != '':
#    print('测试失败!')
#elif MyFunction.trim('    ') != '':
#    print('测试失败!')
#else:
#    print('测试成功!')

#from collections import Iterable;
#print(isinstance(123,int))
#print(MyFunction.minandmax([3,2,4,6,2,4,1]));

import os
#l=[d for d in os.listdir('.')]
#print(l)
#m=os.listdir()
#print(m)
#l1='ABC'
#l2='123'
#l3='LMN'
#l=[a+b if a=='A' or b=='2'  else a+b+c for a in l1 for b in l2 for c in l3]
#print(l)
#L = ['Hello', 'World', 18, 'Apple', None]
#l=[s.lower() if isinstance(s,str) else s for s in L]
#print(l)
#l=[s.lower() for s in L if isinstance(s,str)]
#print(l)
#g=(a+b if a=='A' or b=='2'  else a+b+c for a in l1 for b in l2 for c in l3)

#n = 0
#results = []
#for t in MyFunction.triangles():
#    results.append(t)
#    n = n + 1
#    if n == 20:
#        break

#for t in results:
#    print(t)
from collections import Iterator
from functools import reduce
#l=[1,2,3,4,5]
#r=map(MyFunction.f,l)
#print(list(r))
#print(reduce(MyFunction.product,l))
#L1 = ['adam', 'LISA', 'barT','','l']
#print(list(map(MyFunction.normalize,L1)))
#print('3 * 5 * 7 * 9 =', MyFunction.prod([3, 5, 7, 9]))
#print(list(filter(MyFunction.isf,range(100))))
n='1'
print(n,'-----',n[1:0])


#print('123'[:1],'123'[-1:])

print(list(filter(MyFunction.is_palindrome, range(100))))


L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]

print(sorted(L,key=MyFunction.by_name))

counts=MyFunction.createCounter()
print(counts)
print(counts(),counts(),counts(),counts())

L=list(map(lambda x:x[1]+1,L))
print(L)
L = list(filter(lambda x:x%2, range(1, 20)))
print(L)
import time
print(MyFunction.int2('100'))
print(MyFunction.strftime(time.localtime()))

import sys
print(sys.path)



from class1 import *
p1=people('asdas',12)
p2=people('adas',123)
p1.printinfo()
print(p1.get_age())
p1.set_age(10)
print(p1.get_age())
#p1.set_age(-1)
print(p1.get_age())
bart = Student('Bart Simpson', 59)
lisa = Student('Lisa Simpson', 87)
bart.print_score()
lisa.print_score()
bart.aaa='asasa'

c1=Chinese('lcz',28,False)
c1.printinfo()
c1.isc=True
c1.printinfo()
print(c1.get_age())

c1.set_age(15)
c1.printinfo()

for x in range(10):
    c1=Chinese('lcz'+str(x),28,False)

s=Screen(10,20)
#s.width=1024
#s.height=768
print(s._width,s._height)
print(s.width,s.height)
print('resolution =', s.resolution)
if s.resolution == 786432:
    print('测试通过!')
else:
    print('测试失败!')
print(str(s))

a, b,c = 2, 10,0
print(a,b,c)
for x in range(10):
    a, b,c = b, a + b,a-b
    print(a,b,c)

print(china().aaa('bbb').ccc)
#print(callable(a))
print(china().aaa.bbb.ccc)

from enum import Enum

Month=Enum('月份',('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
for name,member in Weekday.__members__.items():
    print(name,'=>',member,',',member.value)
print(Weekday.Fri,Weekday.Fri.value,Weekday.Fri.name)
a=Weekday.Fri
print(a)
sss(Weekday.Fri)
print(sss(Weekday.Fri)._weekday.name)
aaaa=type(c1)
print(type(c1))


from functools import reduce
import logging
#logging.basicConfig(level = logging.WARN,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
def str2num(s):
    return int(s)

def calc(exp):
    ss = exp.split('+')
    ns = map(str2num, ss)
    return reduce(lambda acc, x: acc + x, ns)

#def main():
#    r = calc('100 + 200 + 345')
#    print('100 + 200 + 345 =', r)
#    r = calc('99 + 88 + 7.6')
#    print('99 + 88 + 7.6 =', r)
#try:
#    main()
#except Exception as e:
#    logging.exception(e)
#finally:
#    print('出现错误')


    
#logger = logging.getLogger(__name__)
#logger.setLevel(level = logging.INFO)
#handler = logging.FileHandler("log.txt")
#handler.setLevel(logging.INFO)
#formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
#handler.setFormatter(formatter)
#logger.addHandler(handler)

#console=logging.StreamHandler()
#console.setLevel(logging.DEBUG)
#logger.addHandler(console)
     
#logger.info("Start print log")
#logger.debug("Do something")
#logger.warning("Something maybe fail.")
#logger.info("Finish")
#try:
#    f=open('log.txt','r')
#    #a=f.read()
#    print(f.read())
#except Exception as e:
#    print(e)
#finally:
#    f.close()
#with open(r'C:\Users\Administrator\Pictures\Camera Roll\logo.png','a+') as f:
#     f.write('Hello World!')
#with open(r'C:\Users\Administrator\Pictures\Camera Roll\logo.png','rb') as f:    
#    a=f.read()
#    print(a)
#    from io import BytesIO
#    bio = BytesIO()
#    bio.write(a)
#    print(bio.getvalue())
#    print(bio.tell())
#    bio.seek(-1,1)
#    print(bio.tell())
#    for i in bio.readlines():
#        print(i.strip())
import os

#for x in os.environ:
#    print(x,':',os.environ[x])

print(os.environ.get('PATH'))
absp=os.path.abspath('.')
print(os.path.join(absp,'hahah'))

#for x in os.listdir('.'):
#    if os.path.isfile(x) and os.path.splitext(x)[1]=='.py':
#         print(x)        
#print([x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py'])

#MyFunction.dir('s')

#import json
#str=json.dumps(dict(name='刘承志',age=15,hasj='asd'),ensure_ascii=False)
#print(str)
#print(json.loads(str))
#str=json.dumps(Student('name',50),default=lambda obj:obj.__dict__)
#print(str)
#n=json.loads(str)

#from multiprocessing import Process


print('\r\n')
print('\r\n')
print('\r\n')
print('\r\n')

from multiprocessing import Pool
import os, time, random
def run_proc(name):
    print('%s-子进程  (%s)...' % (name, os.getpid()))
    start=time.time()
    time.sleep(random.random()*3)
    end=time.time()
    print('%s-子进程耗时 %s 秒 ' % (name,(end-start)))



def long_time_task(name):
    print('Run task %s (%s)...' % (name, os.getpid()))
    start = time.time()
    time.sleep(random.random() * 3)
    end = time.time()
    print('Task %s runs %0.2f seconds.' % (name, (end - start)))

#if __name__=='__main__':
#    print('父进程 %s.' % os.getpid())
#    p=Pool(4)
#    for x in range(5):
#        p.apply_async(run_proc,args=(x,))
#    print('等待所有子进程执行完毕……')
#    p.close()
#    p.join()
#    print('所有进程已执行完毕')




#if __name__=='__main__':
#    print('Parent process %s.' % os.getpid())
#    p = Pool(4)
#    for i in range(5):
#        p.apply_async(run_proc, args=(i,))
#    print('Waiting for all subprocesses done...')
#    p.close()
#    p.join()
#    print('All subprocesses done.')

#import subprocess

#print('$ nslookup www.python.org')
#r = subprocess.call(['nslookup', 'www.python.org'])
#print('Exit code:', r)


#print('$ nslookup')
#p = subprocess.Popen(['nslookup'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
#output, err = p.communicate(b'set q=mx\npython.org\nexit\n')
#print(output.decode('utf-8'))
#print('Exit code:', p.returncode)


from multiprocessing import Process, Queue
import os, time, random

# 写数据进程执行的代码:
def write(q):
    print('Process to write: %s' % os.getpid())
    for value in ['A', 'B', 'C']:
        print('Put %s to queue...' % value)
        q.put(value)
        time.sleep(random.random())

# 读数据进程执行的代码:
def read(q):
    print('Process to read: %s' % os.getpid())
    while True:
        value = q.get(True)
        print('Get %s from queue.' % value)

#if __name__=='__main__':
#    # 父进程创建Queue，并传给各个子进程：
#    q = Queue()
#    pw = Process(target=write, args=(q,))
#    pr = Process(target=read, args=(q,))
#    # 启动子进程pw，写入:
#    pw.start()
#    # 启动子进程pr，读取:
#    pr.start()
#    # 等待pw结束:
#    pw.join()
#    # pr进程里是死循环，无法等待其结束，只能强行终止:
#    pr.terminate()
import threading
def loop():
    print('线程【%s】正在运行' % (threading.current_thread().name))
    n=0
    while n<5:
        n=n+1
        print('线程【%s】正在运行%s' % (threading.current_thread().name,n))
        time.sleep(1)
    print('线程【%s】结束' % (threading.current_thread().name))

##print('线程【%s】正在运行' % (threading.current_thread().name))
#t=threading.Thread(target=loop)
#t.start()
#t.join()
#print('线程【%s】结束' % (threading.current_thread().name))

#def loop1():
#    print('thread %s is running...' % threading.current_thread().name)
#    n = 0
#    while n < 5:
#        n = n + 1
#        print('thread %s >>> %s' % (threading.current_thread().name, n))
#        time.sleep(1)
#    print('thread %s ended.' % threading.current_thread().name)

#print('thread %s is running...' % threading.current_thread().name)
#t = threading.Thread(target=loop, name='LoopThread')
#t.start()
#t.join()
#print('thread %s ended.' % threading.current_thread().name)
lock=threading.Lock()
banlace=0
def change_it(n):
    global banlace
    banlace=banlace+n
    banlace=banlace-n
def runchaneg():
    for x in range(1000000):
        lock.acquire()
        try:
            change_it(x)
        finally:
            lock.release()
#t1=threading.Thread(target=runchaneg)
#t2=threading.Thread(target=runchaneg)
#t1.start()
#t2.start()
#t1.join()
#t2.join()
#print(banlace)

import multiprocessing

print(multiprocessing.cpu_count())

import threading, multiprocessing

#def loop():
#    x = 0
#    while True:
#        x = x ^ 1

#for i in range(multiprocessing.cpu_count()):
#    t = threading.Thread(target=loop)
#    t.start()

#local_base=threading.local()

#def process_s():
#    s=local_base.s
#    print('%s in %s' % (s,threading.current_thread().name))
#def process_f(name):
#    local_base.s=name
#    process_s()
#p1=threading.Thread(target=process_f,args=('哈哈哈',))
#p2=threading.Thread(target=process_f,args=('嘿嘿嘿',))
#p1.start()
#p2.start()
#p1.join()
#p2.join()

from WindowsService import *
severname='MySql'
#Read(severname)
#if IsRuning(severname):
#    print(severname,'正在运行')
#    Stop(severname)
#    Read(severname)
#Read(severname)
#if IsSTOPPED(severname):
#    Start(severname)
#    Read(severname)
import requests
#url='https://www.liaoxuefeng.com/wiki/1016959663602400/1183249464292448'
#r=requests.get(url,headers={'User-Agent': ''})
#if r.status_code==200:
#    print(r.text)
import chardet
c=chardet.detect('Hello, world!'.encode())
print(c)
c=chardet.detect('离离原上草，一岁一枯荣'.encode())
print(c)
c=chardet.detect('最新の主要ニュース'.encode('euc-jp'))
print(c)
#chardet.detect(b'Hello, world!')

#import psutil
#print(psutil.cpu_count())
#print(psutil.cpu_count(logical=False))
#print(psutil.cpu_times())
##for x in range(10):
##    print(psutil.cpu_percent(interval=1,percpu=True))
#print(psutil.virtual_memory())
#print(psutil.disk_partitions())

#print(psutil.test())
print(sys.executable)

print(sys.argv)
print(__file__)


from collections import namedtuple
point=namedtuple('Point',['x','y'])
p=point(1,5)
from collections import deque
q=deque(['rew','er','as'])
print(q)
q.append('last')
print(q)
q.appendleft('before')
print(q)
q.insert(-1,'0')
print(q[1])
from collections import defaultdict
dd=defaultdict(lambda:'N/A')
dd['x']='a'
print(dd['xx'])
from collections import Counter
c = Counter('acabab')
print(c)

import hashlib
h=hashlib.md5()
h.update('123'.encode())
h.update('456'.encode())

h1=hashlib.md5()
h1.update('123456'.encode())
print(h1.hexdigest())
print(h.hexdigest())

import struct

bmp_header = b'\x42\x4d\x38\x8c\x0a\x00\x00\x00\x00\x00\x36\x00\x00\x00\x28\x00\x00\x00\x80\x02\x00\x00\x68\x01\x00\x00\x01\x00\x18\x00'

print(struct.unpack('<ccIIIIIIHH', bmp_header))
from contextlib import contextmanager
@contextmanager
def cccc(name):
    print('<%s>' % name)
    yield
    print('</%s>' % name)

with cccc('hahha'):
    print('adas')
from contextlib import closing
from urllib.request import urlopen
with closing(urlopen('https://www.baidu.com')) as page:
    
    for x in page:
        print(x)
from urllib import request
import json
from html.parser import HTMLParser
from html.entities import name2codepoint
from Student import *
#with request.urlopen('https://www.liaoxuefeng.com/wiki/1016959663602400/1019223241745024') as f:
#    data=f.read()
#    print('Status:',f.status,f.reason)
#    for k,v in f.getheaders():
#        print('%s : %s' % (k,v))
#    print(data.decode())
#req =request.Request('https://www.liaoxuefeng.com/wiki/1016959663602400/1019223241745024')
#req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0')
#with request.urlopen(req) as f:
#    print('Status:',f.status,f.reason)
#    for k,v in f.getheaders():
#        print('%s : %s' % (k,v))
#    print('\r\n')
#    print('\r\n')
#    print('\r\n')
#    Parser= MyHTMLParser()
#    Parser.feed(f.read().decode())
  


#import socket
#s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#s.connect(('z.sumszw.com',80))
#s.send(b'GET / HTTP/1.1\r\nHost: z.sumszw.com\r\nConnection: close\r\n\r\n')
#buffer=[]
#while True:
#    d=s.recv(1024)
#    if d:
#        buffer.append(d)
#    else:
#        break
#data=b''.join(buffer)
#s.close()
#header,html=data.split(b'\r\n\r\n',1)
#print(html)
#print(header.decode('utf-8'))
#with open('sumszw.html','wb') as f:
#    f.write(html)